package top.huntwolf.admin.config;

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.huntwolf.admin.converter.EnumConverter;
import top.huntwolf.admin.converter.StringToEnumConverterFactory;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

@Configuration
public class ConverterConfig implements WebMvcConfigurer {

    @Bean
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter(FastJsonConfig config){
//        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//        converter.setFastJsonConfig(config);
//        converter.setDefaultCharset(StandardCharsets.UTF_8);
//        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
//        return converter;
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        fastConverter.getFastJsonConfig().setSerializerFeatures(SerializerFeature.WriteEnumUsingToString);
        return fastConverter;
    }

    @Bean
    public FastJsonConfig fastJsonConfig(@Qualifier("enumValues")List<Class<?>> enumValues){
        FastJsonConfig config = new FastJsonConfig();
        config.setFeatures(Feature.SupportAutoType);
        config.setSerializerFeatures(SerializerFeature.WriteClassName);
        if (enumValues != null && enumValues.size() > 0){
            // 枚举类型字段：序列化反序列化配置
            EnumConverter converter = new EnumConverter();
            ParserConfig parserConfig = config.getParserConfig();
            SerializeConfig serializeConfig = config.getSerializeConfig();
            for (Class<?> clazz : enumValues) {
                parserConfig.putDeserializer(clazz,converter);
                serializeConfig.put(clazz,converter);
            }
        }

        return config;
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new StringToEnumConverterFactory());
    }
}
